/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.job.snailjob;

import com.aizuda.snailjob.client.job.core.annotation.JobExecutor;
import com.aizuda.snailjob.client.job.core.dto.JobArgs;
import com.aizuda.snailjob.client.model.ExecuteResult;
import com.comac.ins.common.core.exception.base.BaseException;
import com.comac.ins.isfd.domain.IsfdDatabaseMongoQuery;
import com.comac.ins.isfd.domain.IsfdMeshModelBdfParseInfo;
import com.comac.ins.isfd.service.IIsfdMeshModelParseService;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * 数据源数据集成任务调度执行器
 */
@Slf4j
@Component
@JobExecutor(name = "isfdBdfParseJobExecutor")
public class IsfdBdfParseJobExecutor {
    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Autowired
    private IIsfdMeshModelParseService bdfParseService;

    public ExecuteResult jobExecute(JobArgs jobArgs) {
        Date nowTime = new Date();
        // 查询数据
        IsfdDatabaseMongoQuery queryCondition = new IsfdDatabaseMongoQuery();
        List<Document> uploads = bdfParseService.queryList(queryCondition);
        if (CollectionUtils.isEmpty(uploads)) {
            log.error("没有BDF文件，任务调度完成");
            throw new BaseException("没有BDF文件，任务调度完成");
        }

        List<String> ids = uploads.stream()
            .map(document -> {
                Object idObj = document.get("_id");
                if (idObj instanceof ObjectId) {
                    return ((ObjectId) idObj).toHexString();
                }
                return idObj.toString();
            })
            .toList();
        Set<String> existingIdSet = bdfParseService.checkIfTasksExist(ids);
        List<Document> newTasks = uploads.stream()
            .filter(document -> {
                Object idObj = document.get("_id");
                String idStr = idObj instanceof ObjectId
                    ? ((ObjectId) idObj).toHexString()
                    : idObj.toString();
                return !existingIdSet.contains(idStr);
            })
            .toList();

        if (CollectionUtils.isEmpty(newTasks)) {
            log.info("没有未结构化的BDF文件，任务调度完成");
        }

        // 保存解析任务信息
        List<IsfdMeshModelBdfParseInfo> parseInfoList = new ArrayList<>();
        for (Document document : newTasks) {
            String id = document.get("_id").toString();
            IsfdMeshModelBdfParseInfo parseInfo = new IsfdMeshModelBdfParseInfo();
            parseInfo.set_id(new ObjectId(id));
            parseInfo.setStatus(1);
            parseInfoList.add(parseInfo);
        }
        bdfParseService.saveBdfParseInfo(parseInfoList);



        //一个线程一个任务
        for (Document document : newTasks) {
            String id = document.get("_id").toString();
            threadPoolTaskExecutor.execute(() -> {
                try {
                    log.info("BDF结构化开始，id: " + id);
                    bdfParseService.parseAndSaveBdf(id, null);
                } catch (Exception e) {
                    log.error("BDF结构化失败：" + e.getMessage(), e);
                }
            });
        }
        return ExecuteResult.success("结构化开始，任务调度执行完成！");
    }
}
